/*
 * Application.cpp
 *
 *  Created on: 16/06/2014
 *      Author: Vitor
 */

#include "Application.h"

Application::Application() {
	// Arrumando o Eclipse que n�o deixa printar no console
	setvbuf(stdout, NULL, _IONBF, 0);

	if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
		fprintf(stderr, "SDL_Init: %s\n", SDL_GetError());
		exit(1);
	}
	if (SDLNet_Init() < 0) {
		fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError());
		exit(1);
	}
}

Application::~Application() {
	SDLNet_Quit();
	SDL_Quit();
	delete (Globals::file_table.get());
}

void Application::run() {
	std::vector<Thread> system_threads;

	system_threads.push_back(Thread([] () {
		WebServer web_server(8080);
		web_server.run();
	}));
	system_threads.push_back(Thread([] () {
		FileProtocolServer protocol_server;
		protocol_server.run();
	}));
	system_threads.push_back(Thread([] () {
		IdentificatorReceiver identificator_receiver;
		identificator_receiver.run();
	}));
	system_threads.push_back(Thread([] () {
		KeepAliveReceiver receiver;
		receiver.run();
	}));
	system_threads.push_back(Thread([] () {
		IdentificationSender identificator_sender;
		identificator_sender.run();
	}));
	system_threads.push_back(Thread([] () {
		KeepAliveSender sender;
		sender.run();
	}));
	system_threads.push_back(Thread([] () {
		LifeTimeoutManager timeout_manager;
		timeout_manager.run();
	}));

	for (auto& thread : system_threads) {
		thread.start();
	}

	for (auto& thread : system_threads) {
		thread.join();
	}
}
